import re
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from users.models import User
# Create your views here.


class ChangePasswordView(APIView):
    """
    重置密码
    1,获取数据通过url进入此视图函数(仅允许登陆用户进入)
    2,获取当前user的信息,进行当前密码的校验
    3,输入的两次新密码输入一致且满足正则要求则修改密码
    4,修改成功,返回201.
    """
    permission_classes = [IsAuthenticated]

    def put(self, request, user_id):
        user = User.objects.get(id=user_id)
        old_password = request.data.get("old_password")
        if not user.check_password(old_password):
            return Response({'message': "当前密码填写错误"}, status=status.HTTP_400_BAD_REQUEST)
        new_password = request.data.get("password")
        new_password2 = request.data.get("password2")
        if new_password != new_password2 or (not re.match(r'^[0-9a-zA-Z+]{8,20}$', new_password)):
            return Response({'message': "新密码格式不符合要求"}, status=status.HTTP_400_BAD_REQUEST)
        user.set_password(new_password)
        user.save()
        return Response({'message': "密码修改成功"}, status=status.HTTP_201_CREATED)
